<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=meWpk6T4jHKOLxgpj3gvbvj86yFEuXXg"></script>
    <title>添加行政区划</title>
    <style scoped>

        /* .cooperate{
          width: 100%;
          height: 100%;
        } */

        .haeder_box{
            width: 100%;
            height: 47px;
            border-bottom: 1px solid #EEEEEE;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0px 15px;
            box-sizing: border-box;
            overflow: hidden;
        }

        .haeder_title{
            display: flex;

        }
        .haeder_title p{
            margin-left: 8px;
        }

        .content_box{
            width: 100%;
            height: 100%;
            /* background: #ccc; */
            padding: 10px;
            position: relative;
        }

        .bian{
            width: 100px;
            height: 30px;
            position: absolute;
            top: 15px;
            right: 15px;
        }
        .tableData{
            width: 420px;
            position: absolute;
            top: 50px;
            right: 15px;
        }

        /* .ivu-form{
            display: flex;
            flex-wrap: wrap;
        } */
        .ivu-form-item{
            margin-bottom: 5px;
        }

        .hidden_box{
            width: 100%;
            height: 40px;
        }
        #allmap{
            background: red;
            height: 600px;
        }

        .meteorological{
            height: 150px;
            margin-bottom: 10px;
            border: 1px solid #e8eaec;
        }
    </style>

</head>
<body>
<div id="allmap"></div>
</body>
</html>

<script type="text/javascript">

    var province="广东省";
    // 百度地图API功能
    var zoom=10;
    /**
     0: 表示查询省份数据，以地市纬度汇总
     1：表示查询地市数据，以区汇总
     2：表示查询区数据，以街道汇总
     3：表示查看街道，直接打点显示
     */
    var lastType=0;
    var mousePoint;

    // 创建地址解析器实例
    var geocoder = new BMap.Geocoder();  //初始化，Geocoder类
    var map = new BMap.Map("allmap");
    map.centerAndZoom(province, zoom);
    map.enableScrollWheelZoom();
    var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
    var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
    map.addControl(top_left_control);
    map.addControl(top_left_navigation);


    /*注册事件*/
    /*
    if(document.addEventListener){
        document.addEventListener('DOMMouseScroll',scrollFunc,false);
    }
    window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome
    */
    map.addEventListener("zoomend",scrollFunc);

    map.addEventListener("mousemove",mousemoveFunc);

    function mousemoveFunc(e)
    {
        mousePoint=e.point;
    }

    function scrollFunc(e)
    {
        e=e || window.event;

        console.log(map.getZoom());

        var zoom = map.getZoom();

        var newType = getMapType(zoom);
        if(newType==lastType)
        {
            console.log(e.target.getCenter());
            return;
        }

        lastType=newType;

        clearOverlays();




        if(mousePoint==null)
        {
            var center =e.target.getCenter();
            mousePoint = new BMap.Point(e.target.dc.lng, e.target.dc.lat);
        }


        geocoder.getLocation(mousePoint, function (rs) {   //getLocation函数用来解析地址信息，分别返回省市区街等

            var addComp = rs.addressComponents,
                province = addComp.province,//获取省份
                city = addComp.city,//获取城市
                district = addComp.district,//区
                street = addComp.street,//街
                streetNumber = addComp.streetNumber ;

            location_name = province + city + district + street + streetNumber;
            console.log(location_name)
            if(lastType==0)
            {
                statisticsCity(province);//市汇总
            }
            else if(lastType==1)
            {
                statisticsDistrict(province,city);//区汇总
            }
            /*else if(lastType==2)
            {

                loadPoint(province,city,district);//地图海量打点
            }*/


            return location_name;
        });

    }


    statisticsCity(province);

    function statisticsCity(province)
    {
        console.log("市汇总");
        //clearOverlays();
        //#TODO 异步加载数据
        var data = [
            {"id":"0cf21f99968711ea9a37005056360d90","province":"广东省","city":"佛山","total":2,"yellow":0,"red":1,"createdOn":null,"createdByUserName":null,"updatedOn":null,"updatedByUserName":null},
            {"id":"0cf32f61968711ea9a37005056360d90","province":"广东省","city":"中山","total":1,"yellow":0,"red":0,"createdOn":null,"createdByUserName":null,"updatedOn":null,"updatedByUserName":null},
            {"id":"0cf3c8a1968711ea9a37005056360d90","province":"广东省","city":"广州","total":3,"yellow":1,"red":1,"createdOn":null,"createdByUserName":null,"updatedOn":null,"updatedByUserName":null}
        ];

        for(var i=0;i<data.length;i++)
        {
            var item=data[i];
            var province = item.province;
            var city = item.city;
            setRegion(item,lastType);
            setComplexCustomOverlay(province,city,null,null,lastType,item);
        }
    }

    function statisticsDistrict(province,city)
    {
        console.log("区汇总");
        //clearOverlays();
        //#TODO 异步加载数据
        var data = [
            {
                "id": "2e79c1369f2011ea9a37005056360d90",
                "province": "广东省",
                "city": "广州市",
                "district": "天河区",
                "total": 1,
                "green": 1,
                "yellow": 0,
                "red": 0,
                "createdOn": "2020-05-26T20:11:55.000+0000",
                "createdByUserName": "HUJUNMIN",
                "updatedOn": "2020-05-26T20:11:55.000+0000",
                "updatedByUserName": "HUJUNMIN"
            },
            {
                "id": "b838c71f9f1f11ea9a37005056360d90",
                "province": "广东省",
                "city": "广州市",
                "district": "越秀区",
                "total": 1,
                "green": 1,
                "yellow": 0,
                "red": 0,
                "createdOn": "2020-05-26T20:08:37.000+0000",
                "createdByUserName": "HUJUNMIN",
                "updatedOn": "2020-05-26T20:08:37.000+0000",
                "updatedByUserName": "HUJUNMIN"
            }
        ];

        for(var i=0;i<data.length;i++)
        {
            var item=data[i];
            var province = item.province;
            var city = item.city;
            var district = item.district;

            setRegion(item,lastType);
            setComplexCustomOverlay(province,city,district,null,lastType,item);
        }
    }



    function loadPoint(province,city,district,street)
    {
        console.log("地图打点");
        //clearOverlays();
        //#TODO 异步加载数据
        var data ={
            "normal": [],
            "yellow": [
                {
                    "id": "5dfbe9bc964e11ea9a37005056360d90",
                    "historyLocationId": null,
                    "equipmentId": "35331a5395ac11ea9a37005056360d90",
                    "no": "bd-gz-001",
                    "longitude": 113.271393,
                    "latitude": 23.136333,
                    "province": null,
                    "city": null,
                    "address": "广州市政府1塔",
                    "monitorOn": "2020-05-14T08:17:01.000+0000",
                    "level": "YELLOW",
                    "createdOn": null,
                    "createdByUserName": null,
                    "updatedOn": null,
                    "updatedByUserName": null
                }
            ],
            "red": []
        };

        addOverlays(data.normal,"#008000")
        addOverlays(data.yellow,"#ffff00")
        addOverlays(data.red,"#ff0000")
    }

    function addOverlays(data,color)
    {
        if(data==null || data.length==0)
        {
            return;
        }

        if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
            var points = [];  // 添加海量点数据
            for (var i = 0; i < data.length; i++) {
                var point = new BMap.Point(data[i].longitude, data[i].latitude);
                point.mydata = data[i];
                points.push(point);
            }
            var options = {
                size: BMAP_POINT_SIZE_HUGE,
                shape: BMAP_POINT_SHAPE_RHOMBUS,
                color: color
            }
            var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection

            pointCollection.addEventListener('click', function (e) {
                //alert('单击点的坐标为：' + e.point.lng + ',' + e.point.lat);  // 监听点击事件
                var opts = {
                    width : 200,     // 信息窗口宽度
                    height: 170,     // 信息窗口高度
                    title : "<b>站点信息</b>" , // 信息窗口标题
                    enableMessage:true,//设置允许信息窗发送短息
                    message:""
                }
                var item =e.point.mydata;
                var message ="编号: <b>"+item.no+"</b><br/>地址: "+item.address+"<br/>经度: "+item.longitude+"<br/>纬度: "+item.latitude+"<br/>级别: "+item.level+"<br/>时间: "+item.monitorOn+"<br/>";
                var infoWindow = new BMap.InfoWindow(message, opts);  // 创建信息窗口对象

                map.openInfoWindow(infoWindow,point); //开启信息窗口
            });
            map.addOverlay(pointCollection);  // 添加Overlay
        } else {
            alert('请在chrome、safari、IE8+以上浏览器查看本示例');
        }
    }

    function clearOverlays(){
        map.clearOverlays();
    }


    // 复杂的自定义覆盖物
    function ComplexCustomOverlay(point, data,mapType) {
        this._point = point;
        this._data = data;
        this._mapType=mapType;
    }
    ComplexCustomOverlay.prototype = new BMap.Overlay();
    ComplexCustomOverlay.prototype.initialize = function (map) {
        this._map = map;
        var div = this._div = document.createElement("div");
        div.style.position = "absolute";
        div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
        div.style.backgroundColor = "#059c49";
        // div.style.border = "1px solid #EF1B1C";
        div.style.borderRadius = "50%";
        div.style.display = "flex";
        div.style.flexDirection = "column";
        div.style.justifyContent = "center";
        div.style.alignItems = "center";
        div.style.color = "#FFFFFF";
        div.style.height = "65px";
        div.style.width = "65px";
        div.style.padding = "2px";
        div.style.whiteSpace = "nowrap";
        div.style.MozUserSelect = "none";
        div.style.fontSize = "12px";
        div.style.opacity = ".9";




        var region =getRegion(this._mapType,this._data);

        div.setAttribute("region", region);

        var pTitle = document.createElement("p");
        var spanTitle = document.createElement("span");
        spanTitle.setAttribute("name", "title")
        spanTitle.appendChild(document.createTextNode(region));
        pTitle.appendChild(spanTitle);
        div.appendChild(pTitle);

        var pNumber = document.createElement("p");
        var spanpNumber = document.createElement("span");
        spanpNumber.setAttribute("name", "number")
        spanpNumber.appendChild(document.createTextNode(this._data.total));
        pNumber.appendChild(spanpNumber);
        div.appendChild(pNumber);

        var that = this;

        div.onmouseover = function () {
            // this.style.borderColor = "#EF1B1C";
            this.style.backgroundColor = "#EF1B1C";
            this.style.color = "#FFFFFF";
            this.style.opacity = ".9";
            this.style.zIndex = 99999

            var overlays = map.getOverlays();
            for (var i = 0; i < overlays.length; i++) {
                var item = overlays[i];
                if ((item instanceof ComplexCustomOverlay) == false) {
                    if (item.region == getRegion(that._mapType,that._data))
                        item.show();
                    else
                        item.hide()
                }
            }
        }

        div.onmouseout = function () {
            this.style.backgroundColor = "#059c49";
            this.style.color = "#ffffff";
            this.style.opacity = ".9";
            // this.style.borderColor = "#059c49";
            this.style.zIndex = 9999

            var overlays = map.getOverlays();
            for (var i = 0; i < overlays.length; i++) {
                var item = overlays[i];
                if ((item instanceof ComplexCustomOverlay) == false) {
                    item.hide()
                }
            }
        }

        div.onclick = function () {
            var region = that._data.province+" "+that._data.city;
            if(that._data.district != null && that._data.district  != "")
                region = region+" "+that._data.district;
            if(that._data.street != null && that._data.street != "")
                region = region+" "+that._data.street;
            //alert(region);
        }

        map.getPanes().labelPane.appendChild(div);

        return div;
    }
    ComplexCustomOverlay.prototype.draw = function () {
        var map = this._map;
        var pixel = map.pointToOverlayPixel(this._point);
        //alert(this._div.style.width)
        this._div.style.left = pixel.x  -33 + "px";
        this._div.style.top = pixel.y  -33 + "px";
    }

    function getRegion (mapType,data){
        var region = "";
        if(mapType==0)
        {
            region=data.city;
        }
        else if(mapType==1)
        {
            region=data.district;
        }
        else if(mapType==2)
        {
            region=data.street;
            if(region==null || region=="")
            {
                region=data.district;
            }
        }
        return region;
    }

    function getAddress (mapType,data){
        var address = "";
        if(mapType==0)
        {
            address=data.province + data.city;
        }
        else if(mapType==1)
        {
            address=data.province + data.city +data.district;
        }
        else if(mapType==2)
        {
            address=data.province + data.city +data.district;
            if(data.street!=null && data.street!="")
            {
                address+=data.street;
            }
        }
        return address;
    }

    /*
    根据地址获取中心店坐标
    */
    function setComplexCustomOverlay(province,city,district,street,lastType,item)
    {

        var address = null;
        /*
        0: 表示查询省份数据，以地市纬度汇总
        1：表示查询地市数据，以区汇总
        2：表示查询区数据，以街道汇总
        3：表示查看街道，直接打点显示
        */
        if(lastType==0)
        {
            address=province+city;
        }
        else if(lastType==1)
        {
            if(district==null || district=="")
            {
                district = street;
            }
            address=province+city+district;
        }
        else if(lastType==2)
        {
            address=province+city+district+street;
        }
        else
        {
            console.log("setComplexCustomOverlay 不正确的lastType:"+lastType );
        }

        // 创建地址解析器实例
        var myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(address, function(point){
            if (point) {
                var compOverlay = new ComplexCustomOverlay(point,item,lastType);
                map.addOverlay(compOverlay);

                //map.setCenter(point);
            }else{
                console.log("setComplexCustomOverlay 地址:"+address+" 没有解析到结果!");
            }
        }, province);
    }

    function setRegion(item,lastType) {

        var region = getRegion(lastType,item);
        var address =getAddress(lastType,item);
        var bdary = new BMap.Boundary();
        bdary.get(address, rs => {
            var count = rs.boundaries.length;
        for (let i = 0; i < count; i++) {
            var ply = new BMap.Polygon(rs.boundaries[i], {
                strokeWeight: 2, strokeColor: '#ff0000'
            });
            ply.region = region;
            ply.hide();
            this.map.addOverlay(ply);
        }
    });
    }

    /**
     0: 表示查询省份数据，以地市纬度汇总
     1：表示查询地市数据，以区汇总
     2：表示查询区数据，以街道汇总
     3：表示查看街道，直接打点显示
     */
    function getMapType(zoom)
    {
        if(zoom<=10)
        {
            return 0;
        }
        else if(zoom<=12)
        {
            return 1;
        }
        else
        {
            return 2;
        }
    }

</script>